// 认证模块
import api from '@/api'
import router from '@/router'

const state = {
  token: null,
  user: null,
  loading: false
}

const getters = {
  isAuthenticated: state => !!state.token,
  token: state => state.token,
  user: state => state.user,
  userName: state => state.user ? state.user.username : '',
  userRoles: state => state.user ? state.user.roles : [],
  loading: state => state.loading
}

const mutations = {
  // 设置令牌
  SET_TOKEN(state, token) {
    state.token = token
  },
  // 设置用户信息
  SET_USER(state, user) {
    state.user = user
  },
  // 设置加载状态
  SET_LOADING(state, loading) {
    state.loading = loading
  }
}

const actions = {
  // 登录
  async login({ commit, dispatch }, credentials) {
    commit('SET_LOADING', true)
    try {
      const response = await api.auth.login(credentials)
      const { access_token, user } = response.data
      
      commit('SET_TOKEN', access_token)
      commit('SET_USER', user)
      
      // 根据重定向路径导航
      const redirectPath = router.currentRoute.query.redirect || '/'
      router.push(redirectPath)
      
      return response
    } catch (error) {
      console.error('Login error:', error)
      throw error
    } finally {
      commit('SET_LOADING', false)
    }
  },
  
  // 登出
  logout({ commit }) {
    // 清除令牌和用户信息
    commit('SET_TOKEN', null)
    commit('SET_USER', null)
    
    // 跳转到登录页
    router.push('/login')
  },
  
  // 刷新令牌
  async refreshToken({ commit, state }) {
    try {
      const response = await api.auth.refreshToken()
      const { access_token } = response.data
      
      commit('SET_TOKEN', access_token)
      return response
    } catch (error) {
      // 刷新令牌失败，登出
      commit('SET_TOKEN', null)
      commit('SET_USER', null)
      router.push('/login')
      throw error
    }
  },
  
  // 获取当前用户信息
  async fetchCurrentUser({ commit }) {
    try {
      const response = await api.auth.getCurrentUser()
      commit('SET_USER', response.data)
      return response
    } catch (error) {
      console.error('Error fetching current user:', error)
      throw error
    }
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
} 